/*********************************************************************************
 *      Copyright:  (C) 2025 iot25<lingyun@email.com>
 *                  All rights reserved.
 *
 *       Filename:  server.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(03/05/25)
 *         Author:  iot25 <lingyun@email.com>
 *      ChangeLog:  1, Release initial version on "03/05/25 21:49:39"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <pthread.h>
#include <getopt.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/resource.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/stat.h>

#include "sqlite.h"
#include "logger.h"
#include "pack_data.h"

#define LOG_LEVEL_ERROR   0  
#define LOG_LEVEL_WARN    1  
#define LOG_LEVEL_INFO    2  
#define LOG_LEVEL_DEBUG   3

#define MAX_EVENTS 		4096			/* 最大监听事件数 */
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
// 信号处理函数
volatile sig_atomic_t running = 1;

void signal_handler(int sig)
{
    log_info("Server shutdown by signal %d", sig);
    running = 0; // 停止主循环
}


int print_usage(char *progname);
int set_socket_rlimit(void); 
int socket_server_init(char *listen_ip, int listen_port);

// 新增函数：打印查询结果
void print_query_result(packet_t *pack)
{
    if (pack)
	{
        printf("Device ID: %s\n", pack->dev_id);
        printf("Device Time: %s\n", pack->dev_time);
        printf("Device Temperature: %.3f\n", pack->dev_temp);
    }
}

int main(int argc, char **argv)
{
    int                  query_db = 0;
	int 				 listen_fd = -1;								/* socket描述符 */
    int			         conn_fd = -1;									/* accept函数返回值 */
    int 				 serv_port = -1;									/* 监听端口号 */  
	int 				 daemon_run = 0;								/* 后台运行标志 */
    char 				*progname = NULL;								/* 文件名 */
    int  				 opt = 0;										/* 参数解析函数getopt_long返回值 */
    char 				 buf[1024];										/* 接收数据缓冲区 */
    int 				 epoll_rv = -1;									/* epoll函数返回值 */
    struct epoll_event 	 event;											/* epoll事件 */
    struct epoll_event 	 event_array[MAX_EVENTS];						/* epoll事件数组 */
    int 				 events;										/* epoll事件数 */
    packet_t			*pack = NULL;	/* 打包函数结构体 */
    char  				*log_filename = "server.log";					/* 日志文件名 */
    int			         user_log_level = LOG_LEVEL_INFO;
    int  				 log_size = 1024;
    int                  log_lock = 1;

    struct option 		 long_options[] =								/* 解析的参数结构体 */
    {
        {"daemon", no_argument, NULL, 'b'},
        {"port", required_argument, NULL, 'p'},
        {"user_log-level", no_argument, NULL, 'l'},
        {"help", no_argument, NULL, 'h'},
        {"query", no_argument, NULL, 'q'},  // 新增：查询数据库参数
		{NULL, 0, NULL, 0}
    };

    progname = basename(argv[0]);	/* 文件名 */
    /*  Parser the command line parameters */
    while ((opt = getopt_long(argc, argv, "bp:l:h",long_options,NULL))!= -1 )
    {
        printf("[DEBUG] opt=%c (%d), optarg=%s\n", opt, opt, optarg ? optarg : "NULL");
        switch(opt)
        {
            case 'b':
                daemon_run=1;					/* 是否后台运行 */
                break;
            case 'p':
                serv_port = atoi(optarg);		/* 监听的端口号 */
                log_debug("DEBUG: Using port %d\n", serv_port); // 调试输出
                break;

            case 'l':
                user_log_level=atoi(optarg);
                if(user_log_level<LOG_LEVEL_ERROR||user_log_level>LOG_LEVEL_DEBUG)
                {
                    fprintf(stderr,"Loglevelmustbe0-3\n");
                    return EXIT_FAILURE;
                }
                log_debug("Loglevel setto: %d\n",user_log_level);
                break;

            case 'h': 
                print_usage(progname);			/* 说明信息 */
                return EXIT_SUCCESS;
                break;
			 case 'q':
                query_db = 1;  // 新增：设置查询数据库标志
                break;
        }
    }

    
    if (serv_port == 0)
    {
        fprintf(stderr, "Error: Port must be specified with -p\n");
        print_usage(progname);
        return EXIT_FAILURE;
    }


    /* 分配packet内存 */
    pack = (packet_t *)malloc(sizeof(packet_t));
    if (!pack)
    {
        fprintf(stderr, "malloc packet_t failed: %s\n", strerror(errno));
        return EXIT_FAILURE;
    }

	 // 设置信号处理
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);


    log_open(log_filename, user_log_level, log_size , log_lock);	/* 初始化日志：设置日志文件名和记录日志级别 */

    /* 设置最大文件描述符数 */
    if (set_socket_rlimit() < 0)
    {
        log_error("set_socket_rlimit failed");
        goto CleanUp;
    }

    if (db_init() < 0)
    {
        log_error("db_init failed");
        goto CleanUp;
    }

    if( (listen_fd = socket_server_init(NULL, serv_port)) < 0 )
    {	/* 初始化socketi，监听指定的端口号 */
        log_error("[%s: ERROR: %s server listen on port %d failure]\n",   __FILE__, argv[0], serv_port);
        goto CleanUp;
    }
    log_debug("listen successfully\n");

    if( daemon_run )
    {	/* 判断是否后台运行 */
        log_debug("Running as daemon\n");
        daemon(0, 0);
    }
    
	if (query_db)
    {
        packet_t query_pack;
        if (db_query(&query_pack) == 0)
        {
            print_query_result(&query_pack);
        }
        else
        {
            log_error("db_query failed");
        }
        // 若仅查询数据库，可在此处退出程序
        log_info("Query database completed, exiting...");
        goto CleanUp;
    }


    if( (epoll_rv = epoll_create(MAX_EVENTS)) < 0 )
    {	/* 创建epoll监听队列 */
        log_error("[%s: epoll_create() failure: %s]\n",   __FILE__, strerror(errno));
        return -3;
    }

    event.events = EPOLLIN|EPOLLET;	/*边缘触发  */ //仅在fd状态变化时触发一次（如新数据到达），需一次性处理完所有数据。			
    event.data.fd = listen_fd;		

    if( epoll_ctl(epoll_rv, EPOLL_CTL_ADD, listen_fd, &event) < 0)// 将sockfd添加到epoll实例中
    {	/* 创建，增加，监听的文件描述符， */
        log_error("[%s: epoll add listen socket failure: %s]\n",   __FILE__, strerror(errno));
        goto CleanUp;
    }

    /* 主事件循环 */
    while (running)
    {
        events = epoll_wait(epoll_rv, event_array, MAX_EVENTS, -1);
        if (events < 0)
        {
            if (errno == EINTR) 
            {
                log_info("epoll_wait interrupted by signal");
                continue;  /* 被信号中断 */
            }
            log_error("epoll_wait failed: %s", strerror(errno));
            perror("epoll_wait"); // 打印系统错误信息
            break;
        }
        log_debug("epoll_wait returned %d events\n", events); // 打印事件数量

        for (int i = 0; i < events; i++)
        {
            /* 处理错误事件 */
            if (event_array[i].events & (EPOLLERR | EPOLLHUP))
            {
                log_warn("epoll error on fd %d", event_array[i].data.fd);
                close(event_array[i].data.fd);
				continue;
            }
            
            /* 新连接到达 */
            if (event_array[i].data.fd == listen_fd)
            {
                while ((conn_fd = accept(listen_fd, NULL, NULL)) > 0)
                {
                    /* 设置新连接为非阻塞 */
                     log_debug("New connection accepted, fd=%d\n", conn_fd);
					
					 int flags = fcntl(conn_fd, F_GETFL, 0);
                    fcntl(conn_fd, F_SETFL, flags | O_NONBLOCK);

                    event.events = EPOLLIN | EPOLLET;
                    event.data.fd = conn_fd;
					
				
                    if (epoll_ctl(epoll_rv, EPOLL_CTL_ADD, conn_fd, &event) < 0)
                    {
                        log_error("epoll_ctl add client fd failed: %s", strerror(errno));
                        log_error("epoll_ctl\n"); // 打印系统错误信息
                        close(conn_fd);
                        
						continue;
                    }
					else
					{
   						 log_debug("epoll_ctl add client fd successfully\n");
					}

                    log_debug("New client connected: fd=%d", conn_fd);
                }
				

                if (conn_fd < 0 && errno != EAGAIN && errno != EWOULDBLOCK)
                {
				
                    log_error("accept failed: %s", strerror(errno));
                    perror("accept"); // 打印系统错误信息
                }
			
				log_debug("kao\n");
            
			}	/* 处理客户端数据 */
            	int client_fd = event_array[i].data.fd;
            	
				ssize_t bytes_read;
			
            	while ((bytes_read = read(client_fd, buf, sizeof(buf)-1)) > 0)
            	{
                	buf[bytes_read] = '\0';
                	log_debug("Received %zd bytes from fd %d: %s \n", bytes_read, client_fd, buf);
               	 	log_debug("Received data from client (fd=%d): %s\n", client_fd, buf);

                	if (unpack_data(buf, pack) < 0) // 先解包数据
                	{
                    	log_error("unpack_data failed");
                    	continue;
                	}

                	if (db_insert(pack) < 0)
                	{
                    	log_error("db_insert failed");
                	}
            	}
          	    if (bytes_read == 0)
           		{	  /* 客户端关闭连接 */
                	log_info("Client fd %d disconnected", client_fd);
                	close(client_fd);
            	}
            	else if (bytes_read < 0)
            	{
                	if (errno == EAGAIN || errno == EWOULDBLOCK)
                	{
                    	log_info("read from fd %d would block", client_fd);
                	}
                	else
                	{
                    		log_error("read from fd %d failed: %s", client_fd, strerror(errno));
                    		perror("read"); // 打印系统错误信息
                    		close(client_fd);
					}
                }			
        }
    }


CleanUp:
    /* 资源清理 */
    log_info("Server shutting down...");
    if (epoll_rv >= 0) close(epoll_rv);
    if (listen_fd >= 0) close(listen_fd);
    if (pack)
    {
        free(pack);
        pack = NULL;
    }
    db_close(); // 关闭数据库
    log_close();
    return 0;
}

int print_usage(char *progname)
{
    printf("%s usage:\n",progname);
    printf("-p(--port) input the port you will bind\n");
    printf("-d(--daemon) the program will run at background\n");
    printf("-h(--help) print the help massage\n");
    printf("\nExample: %s -b -p 8900\n", progname);
    return 0;
}

int socket_server_init(char *listen_ip, int listen_port)
{
    struct sockaddr_in servaddr;
    int rv = 0;
    int on = 1;
    int listen_fd;

    if ( (listen_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        log_error("Use socket() to create a TCP socket failure: %s\n", strerror(errno));
        return -1;
    }
 	 // 设置端口可重用
    if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) {
        log_error("setsockopt() failure: %s\n", strerror(errno));
        close(listen_fd);
        return -1;
    }
	/*  Set socket port reuseable, fix 'Address already in use' bug when socket server restart */
    setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(listen_port);

    if( !listen_ip ) /*  Listen all the local IP address */
    {
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    }
    else /*  listen the specified IP address */
    {
        if  (inet_pton(AF_INET, listen_ip, &servaddr.sin_addr) <= 0 )
        {
            log_error("inet_pton() set listen IP address failure.\n");
            rv = -2;
            goto CleanUp;
        }
    }
    if( bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 )
    {
        log_error("Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
        rv = -3;
        goto CleanUp;
    }
    if( listen(listen_fd, 64) < 0)
    {
        log_error("Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
        rv = -4;
        goto CleanUp;
    }
CleanUp:
    if( rv<0 )
        close(listen_fd);
    else
        rv = listen_fd;
    return rv;
}

/*  Set open file description count to max */
int set_socket_rlimit(void)
{
    struct rlimit limit = {0};

    getrlimit(RLIMIT_NOFILE, &limit );

    limit.rlim_cur = limit.rlim_max;
    setrlimit(RLIMIT_NOFILE, &limit );
    log_debug("set socket open fd max count to %ld\n", limit.rlim_max);
    return 0;
}



